﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;

namespace Flame.Dlr
{
#if Javascript
    class IronJSCompiler : ICompiler
    {

        CompilerParameters _parameters;
        IronJS.Hosting.CSharp.Context _engine = new IronJS.Hosting.CSharp.Context();
        public IronJSCompiler(CompilerParameters parameters)
        {
            _parameters = parameters;
        }



        public CompilerResult Compile(string script)
        {
            CompilerResult cr = new CompilerResult();
            try
            {
                script = _parameters.Preprocessor(script);
                cr.Data = _engine.Execute(script);
                return cr;
            }
            catch (Exception e)
            {
                cr.Data = e;
                return cr;
            }
        }

        public ResultAssembly AddAssembly(AssemblyInfo res)
        {
            return null;
        }

        public void AddVariable(Variable variable)
        {
            _engine.SetGlobal(variable.Name, variable.Data);
        }


        public CompilerResult[] ClearScope()
        {
            foreach (Variable v in _parameters.Variables)
                AddVariable(v);
            foreach (AssemblyInfo a in _parameters.Assemblies)
                AddAssembly(a);
            List<CompilerResult> cr = new List<CompilerResult>();
            foreach (Script s in _parameters.Scripts)
            {
                if (s.Language == Languages.Javascript)
                    cr.Add(Compile(s.ScriptText));
            }
            return cr.ToArray();
        }

        public Languages Language { get { return Languages.Javascript; } }
    }

#endif
}
